package com.example.meet;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.example.framework.base.BaseUiActivity;
import com.example.framework.bmob.bmobManager.BmobManager;
import com.example.framework.entity.Constants;
import com.example.framework.manager.DialogManager;
import com.example.framework.utils.LogUtils;
import com.example.framework.utils.SpUtils;
import com.example.framework.view.DialogView;
import com.example.meet.fragment.ChatFragment;
import com.example.meet.fragment.LifeFragment;
import com.example.meet.fragment.MeFragment;
import com.example.meet.fragment.MeetFragment;
import com.example.meet.service.CloudService;
import com.example.meet.ui.FirstUploadActivity;

import org.jetbrains.annotations.NotNull;

import java.util.List;

public class MainActivity extends BaseUiActivity implements View.OnClickListener{
    // 相遇
    private ImageView iv_meet;
    private TextView tv_meet;
    private LinearLayout ll_meet;
    private MeetFragment mMeetFragment = null;
    private FragmentTransaction mMeetTransaction = null;

    // 生活
    private ImageView iv_life;
    private TextView tv_life;
    private LinearLayout ll_life;
    private LifeFragment mLifeFragment = null;
    private FragmentTransaction mLifeTransaction = null;

    // 聊天
    private ImageView iv_chat;
    private TextView tv_chat;
    private LinearLayout ll_chat;
    private ChatFragment mChatFragment = null;
    private FragmentTransaction mChatTransaction = null;

    // 我的
    private ImageView iv_me;
    private TextView tv_me;
    private LinearLayout ll_me;
    private MeFragment mMeFragment = null;
    private FragmentTransaction mMeTransaction = null;

    private static final int PERMISSION_REQUEST_CODE = 1000;

    public static final int UPLOAD_REQUEST_CODE = 1002;

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    /**
     * 初始化控件
     */
    private void initView() {
        requestPermission();

        iv_meet = findViewById(R.id.iv_meet);
        tv_meet = findViewById(R.id.tv_meet);
        ll_meet = findViewById(R.id.ll_meet);

        iv_life = findViewById(R.id.iv_life);
        tv_life = findViewById(R.id.tv_life);
        ll_life = findViewById(R.id.ll_life);

        iv_chat = findViewById(R.id.iv_chat);
        tv_chat = findViewById(R.id.tv_chat);
        ll_chat = findViewById(R.id.ll_chat);

        iv_me = findViewById(R.id.iv_me);
        tv_me = findViewById(R.id.tv_me);
        ll_me = findViewById(R.id.ll_me);

        ll_meet.setOnClickListener(this);
        ll_life.setOnClickListener(this);
        ll_chat.setOnClickListener(this);
        ll_me.setOnClickListener(this);

        // 显示文本
        tv_meet.setText(getString(R.string.text_main_meet));
        tv_life.setText(getString(R.string.text_main_life));
        tv_chat.setText(getString(R.string.text_main_chat));
        tv_me.setText(getString(R.string.text_main_me));

        initFragment();
        // 切换默认选项卡
        checkMainTab(0);

        // 检查TOKEN
        checkToken();

        // 模拟数据
//        SimulationData.testData();
    }

    /**
     * 检查TOKEN
     */
    private void checkToken() {
        // 获取TOKEn需要三个参数 1. 用户id 2. 头像地址 3.昵称
        String token = SpUtils.getInstance().getString(Constants.SP_TOKEN, "");
        if (!TextUtils.isEmpty(token)) {
            // 启动云服务去连接融云服务
            startService(new Intent(this, CloudService.class));
        } else {
            // 1. 有三个参数
            String tokenPhoto = BmobManager.getInstance().getUser().getTokenPhoto();
            String tokenName = BmobManager.getInstance().getUser().getTokenNickName();
            if (!TextUtils.isEmpty(tokenPhoto) && !TextUtils.isEmpty(tokenName)) {
                createToken();
            } else {
                // 创建上传提示框
                createUploadDialog();
            }
        }
    }

    /**
     * 创建上传提示框
     */
    private void createUploadDialog() {
        final DialogView uploadDialog = DialogManager.getDialogInstance().initView(this, R.layout.dialog_first_upload);
        // 外部点击不能消失
        uploadDialog.setCancelable(false);
        ImageView iv_go_upload = uploadDialog.findViewById(R.id.iv_go_upload);
        iv_go_upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogManager.getDialogInstance().hideDialog(uploadDialog);
                FirstUploadActivity.startActivity(MainActivity.this, UPLOAD_REQUEST_CODE);
            }
        });
        DialogManager.getDialogInstance().showDialog(uploadDialog);
    }

    /**
     * 创建Token
     */
    private void createToken() {
        LogUtils.e("createToken");
    }

    /**
     * 初始化Fragment
     */
    private void initFragment() {
        // 相遇
        if (mMeetFragment == null) {
            mMeetFragment = new MeetFragment();
            mMeetTransaction = getSupportFragmentManager().beginTransaction();
            mMeetTransaction.add(R.id.mMainLayout, mMeetFragment);
            mMeetTransaction.commit();
        }
        // 生活
        if (mLifeFragment == null) {
            mLifeFragment = new LifeFragment();
            mLifeTransaction = getSupportFragmentManager().beginTransaction();
            mLifeTransaction.add(R.id.mMainLayout, mLifeFragment);
            mLifeTransaction.commit();
        }
        // 聊天
        if (mChatFragment == null) {
            mChatFragment = new ChatFragment();
            mChatTransaction = getSupportFragmentManager().beginTransaction();
            mChatTransaction.add(R.id.mMainLayout, mChatFragment);
            mChatTransaction.commit();
        }
        // 我的
        if (mMeFragment == null) {
            mMeFragment = new MeFragment();
            mMeTransaction = getSupportFragmentManager().beginTransaction();
            mMeTransaction.add(R.id.mMainLayout, mMeFragment);
            mMeTransaction.commit();
        }
    }

    /**
     * 显示Fragment
     * @param mFragment
     */
    private void showFragment(Fragment mFragment) {
        if (mFragment != null) {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            hideAll(transaction);
            transaction.show(mFragment);
            transaction.commitAllowingStateLoss();
        }
    }

    /**
     * 隐藏所有的Fragment，隐藏之后再显示自己想要的那个Fragment
     * @param transaction
     */
    private void hideAll(FragmentTransaction transaction) {
        if (mMeetFragment != null) {
            transaction.hide(mMeetFragment);
        }
        if (mLifeFragment != null) {
            transaction.hide(mLifeFragment);
        }
        if (mChatFragment != null) {
            transaction.hide(mChatFragment);
        }
        if (mMeFragment != null) {
            transaction.hide(mMeFragment);
        }
    }

    /**
     * 切换主页显示卡
     * @param index 0：相遇
     *              1：生活
     *              2：聊天
     *              3：我的
     */
    private void checkMainTab(int index) {
        switch (index) {
            case 0:
                showFragment(mMeetFragment);

                iv_meet.setImageResource(R.drawable.img_star_p);
                iv_life.setImageResource(R.drawable.img_square);
                iv_chat.setImageResource(R.drawable.img_chat);
                iv_me.setImageResource(R.drawable.img_me);

                tv_meet.setTextColor(getResources().getColor(R.color.colorAccent));
                tv_life.setTextColor(Color.GRAY);
                tv_chat.setTextColor(Color.GRAY);
                tv_me.setTextColor(Color.GRAY);

                break;

            case 1:
                showFragment(mLifeFragment);

                iv_meet.setImageResource(R.drawable.img_star);
                iv_life.setImageResource(R.drawable.img_square_p);
                iv_chat.setImageResource(R.drawable.img_chat);
                iv_me.setImageResource(R.drawable.img_me);

                tv_meet.setTextColor(Color.GRAY);
                tv_life.setTextColor(getResources().getColor(R.color.colorAccent));
                tv_chat.setTextColor(Color.GRAY);
                tv_me.setTextColor(Color.GRAY);

                break;

            case 2:
                showFragment(mChatFragment);

                iv_meet.setImageResource(R.drawable.img_star);
                iv_life.setImageResource(R.drawable.img_square);
                iv_chat.setImageResource(R.drawable.img_chat_p);
                iv_me.setImageResource(R.drawable.img_me);

                tv_meet.setTextColor(Color.GRAY);
                tv_life.setTextColor(Color.GRAY);
                tv_chat.setTextColor(getResources().getColor(R.color.colorAccent));
                tv_me.setTextColor(Color.GRAY);

                break;

            case 3:
                showFragment(mMeFragment);

                iv_meet.setImageResource(R.drawable.img_star);
                iv_life.setImageResource(R.drawable.img_square);
                iv_chat.setImageResource(R.drawable.img_chat);
                iv_me.setImageResource(R.drawable.img_me_p);

                tv_meet.setTextColor(Color.GRAY);
                tv_life.setTextColor(Color.GRAY);
                tv_chat.setTextColor(Color.GRAY);
                tv_me.setTextColor(getResources().getColor(R.color.colorAccent));

                break;
        }
    }

    /**
     * Fragment启动优化
     *
     * 防止重叠
     * 当应用的内存紧张的时候，系统会回收Fragment对象
     * 再一次进入的时候会重新创建Fragment
     * 非原来对象，我们无法控制，导致重叠
     * @param fragment
     */
    @Override
    public void onAttachFragment(@NonNull @NotNull Fragment fragment) {
        if (mMeetFragment != null && fragment instanceof MeetFragment) {
            mMeetFragment = (MeetFragment) fragment;
        }
        if (mLifeFragment != null && fragment instanceof LifeFragment) {
            mLifeFragment = (LifeFragment) fragment;
        }
        if (mChatFragment != null && fragment instanceof ChatFragment) {
            mChatFragment = (ChatFragment) fragment;
        }
        if (mMeFragment != null && fragment instanceof MeFragment) {
            mMeFragment = (MeFragment) fragment;
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_meet:
                checkMainTab(0);
                break;

            case R.id.ll_life:
                checkMainTab(1);
                break;

            case R.id.ll_chat:
                checkMainTab(2);
                break;

            case R.id.ll_me:
                checkMainTab(3);
                break;
        }
    }

    private void requestPermission() {
        request(PERMISSION_REQUEST_CODE, new OnPermissionResult() {
            @Override
            public void onSuccess() {

            }

            @Override
            public void onFailed(List<String> mListNoPer) {
                LogUtils.e("noPermission :" + mListNoPer.toString());
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == UPLOAD_REQUEST_CODE) {
                // 说明头像上传成功
                checkToken();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}